package com.qf.Controller;

import com.qf.utils.Constants;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author Wy
 * @version V1.0
 * @Project web人员管理系统
 * @Package com.qf.Controller
 * @Description:
 * @Date 2022/5/27 12:07
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodStr = req.getParameter(Constants.TAG);
        if(methodStr==null||"".equals(methodStr)){
            methodStr=Constants.INDEX;

        }
        Class aClass = this.getClass();
        try {
            Method method = aClass.getMethod(methodStr,HttpServletRequest.class,HttpServletResponse.class);
            String invoke = (String) method.invoke(this, req, resp);
           if(invoke!=null){
               if(invoke.startsWith(Constants.FORWARD)){
                   //7. 判断执行后是请求转发处理
                   //获取路径, 例如: http://localhost:8080/admin/admin.jsp
                   String path = invoke.substring(invoke.indexOf(Constants.FLAG) + 1);
                   //执行请求转发
                   req.getRequestDispatcher(path).forward(req, resp);
               }else  if(invoke.startsWith(Constants.REDIRECT)){
                   //8. 判断执行后是重定向处理
                   //获取路径, 例如: http://localhost:8080/admin/admin.jsp
                   String path= invoke.substring(invoke.indexOf(Constants.FLAG) + 1);
                   resp.sendRedirect(path);
               }
               else{
                   //9. 判断如果是其他类型的返回值, 那么通过流写回到浏览器页面
                   resp.getWriter().println(invoke);

               }
           }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
